package impl

import (
	"context"
	"fmt"
	"time"

	"gitee.com/ChangPaoZhe/devops/apps/token"
	"gitee.com/ChangPaoZhe/devops/apps/user"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/bson"
	user_impl "gitee.com/ChangPaoZhe/devops/apps/user/impl"

)


func DefaultRandom()  string  {
	randomUUID, err := uuid.NewRandom()
	if err != nil {
		panic(err)
	}
	return   randomUUID.String()
}


func DefaultCreaueUser()  *user.User{
	return  &user.User{

	}
}
func  NewDefaultToken()  *token.Token {
	Now_time:=time.Now()
	return &token.Token{
		Id: DefaultRandom(),
		Accesstoken: DefaultRandom(),
		Refreshtoken:  DefaultRandom(),
		CreatedAt: Now_time.Unix(),
		//2h 后的时间
		AccesstokenExpiredate: Now_time.Add(2*time.Hour).Unix(),
		// 7d 后的时间
		RefreshtokenExpiredate: Now_time.Add(7*24*time.Hour).Unix(),
		Status: 1,
	}
}

func  NewDefaultLoginRequest() *token.LoginRequest {
	return &token.LoginRequest{
	}
}

func NewDefaultLogOutResponse() *token.LogOutResponse{
	return &token.LogOutResponse{

	}
}

func NewDefaultLogOutRequest()  *token.LogOutRequest {
	return  &token.LogOutRequest{}
}

func  NewDefaultRequestValidateToken()  *token.RequestValidateToken {
	return &token.RequestValidateToken{}
}

func (t *TokenImpl) Login(ctx  context.Context,req   *token.LoginRequest) (*token.Token, error) {
	// login:=NewDefaultLoginRequest()
	collection:=t.MongDB.Collection("user")
	passreq:=user_impl.NewDefaultCheckPasswordRequest()
	passreq.Username=req.Username
	passreq.Password=req.Password
	ins,err:=t.user.CheckPassword(ctx, passreq)
	if  err != nil {
		return nil, err
	}
	token:=NewDefaultToken()
	token.Role=ins.Role
	token.Username=ins.Username
	collection=t.MongDB.Collection("token")
	_,err=collection.InsertOne(ctx, token)
	if err != nil {
		msg:=fmt.Sprintf(err.Error())
		t.logger.Error().Msg(msg)
		return nil,err
	}
	return token, nil
}
func (t *TokenImpl) Logout(ctx  context.Context,req   *token.LogOutRequest) ( *token.LogOutResponse,error) {
	tokens:=&token.Token{}
	// 刷新token和at token要做确认后才能释放，将其设置为过期token
	if req.Accesstoken==""  ||   req.Refreshtoken=="" {
		msg:=fmt.Sprintf("accesstoken or  refreshtoken is null")
		t.logger.Error().Msg(msg)
		return  nil,fmt.Errorf(msg)
	}
	collection:=t.MongDB.Collection("token")

	filter:=bson.M{"$and": []bson.M{bson.M{"accesstoken": req.Accesstoken},bson.M{"refreshtoken": req.Refreshtoken}}}
	err:=collection.FindOne(ctx,filter).Decode(tokens)
	if  tokens.Status==1  ||    err != nil  {
		msg:=fmt.Sprintf("accesstoken or  refreshtoken check error")
		t.logger.Error().Msg(msg)
		return  nil,fmt.Errorf(msg)
	}
	update:=bson.M{"$set": bson.M{"status": 0}}
	_,err=collection.UpdateOne(ctx, filter,update)
	if 	err != nil {
		t.logger.Error().Msg(err.Error())
		return nil, err
	}
	resp:=&token.LogOutResponse{
		Username: tokens.Username,
	}
	return  resp,nil 
}


func (t *TokenImpl) ValidateToken(ctx context.Context, in *token.RequestValidateToken) (*token.Token, error) {
	// 检查时间，通过accesstoken 查看问题
	if  in.Accesstoken == "" {
		return  nil,fmt.Errorf("not found  access token")
	}
	// 查询token
	tokens:=&token.Token{}
	colloection:=t.MongDB.Collection("token")
	filter:=bson.M{"accesstoken": in.Accesstoken}
	err:=colloection.FindOne(ctx, filter).Decode(tokens)
	if err != nil {
		msg:=fmt.Sprintf("token  %s  not found",in.Accesstoken)
		t.logger.Error().Msg(msg)
		return  nil,fmt.Errorf(msg)
	}
	if  tokens.Status == 0 || tokens.AccesstokenExpiredate<  time.Now().Unix()  {
		msg:=fmt.Sprintf("token  %s  过期",in.Accesstoken)
		t.logger.Error().Msg(msg)
		return  nil,fmt.Errorf(msg)
	}
	return tokens,nil 
}
